package com.suxin.datahub.util;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname LocalCacheUtil
 * @Description [ LocalCacheUtil ]
 * @Author Tang
 * @Date 2020/11/9 17:10
 * @Created by ASUS
 */
public class LocalCacheUtil {

    private static Map<String, CacheValue> cacheMap = new ConcurrentHashMap<>(16);

    private static volatile LocalCacheUtil cacheUtil;

    @Data
    @AllArgsConstructor
    public static class CacheValue{
        /**
         * 单位 秒
         */
        private Long expirationTime;
        private Object value;
    }

    public static LocalCacheUtil getInstance() {

        if (cacheUtil != null) {
            return cacheUtil;
        }

        synchronized (LocalCacheUtil.class) {
            if (cacheUtil == null) {
                return new LocalCacheUtil();
            }
        }
        return cacheUtil;
    }

    public Object get(String key) {
        if (cacheMap.get(key) == null) {
            return null;
        }
        return cacheMap.get(key).getValue();
    }

    public void set(String key,CacheValue cacheValue) {

        cleanTimeOut();

        cacheValue.setExpirationTime(System.currentTimeMillis() + cacheValue.getExpirationTime() * 1000);

        cacheMap.put(key, cacheValue);
    }

    private void cleanTimeOut() {
        Set<String> keySet = cacheMap.keySet();
        keySet.forEach((key) -> {
            CacheValue cacheValue = cacheMap.get(key);
            if (System.currentTimeMillis() >= cacheValue.expirationTime) {
                cacheMap.remove(key);
            }
        });
    }


}